//
//  DWLoginViewController.swift
//  DWater-Swift
//
//  Created by mac on 2017/4/19.
//  Copyright © 2017年 Dimon.胡亚宾. All rights reserved.
//

import UIKit
import PKHUD
import BKSwiftKit
import DeviceUtil
var isShowingLogin : Bool = false
public typealias loginCompletions = () -> Void

class DWLoginViewController: BaseViewController {

    @IBOutlet weak var accountView: UIView!
    @IBOutlet weak var passwordView: UIView!
    @IBOutlet weak var accountField: UITextField!
    @IBOutlet weak var passwdField: UITextField!
    @IBOutlet weak var loginBtn: UIButton!
    
    var loginCompletions : loginCompletions?
    let keyboardHeight : CGFloat = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        let resignControl = UIControl(frame:CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            resignControl.addTarget(self, action: #selector(resignAllTextField(sender:)), for: .touchDown)
            self.view.insertSubview(resignControl, at: 0)
       
            self.loginBtn.layer.cornerRadius = 5.0
            self.accountView.layer.cornerRadius = 5.0
            self.accountView.alpha = 0.5
            self.accountView.layer.borderColor = UIColor.white.cgColor
            self.accountView.layer.borderWidth = 1.0
            self.passwordView.layer.cornerRadius = 5.0
            self.passwordView.alpha = 0.5
            self.passwordView.layer.borderColor = UIColor.white.cgColor
            self.passwordView.layer.borderWidth = 1.0
            self.setPlaceHolerTextColor([self.accountField,self.passwdField])
        
        let lastLoginId = defaults.object(forKey: kSaveMacroUserID)
            if lastLoginId != nil {
                self.accountField.text = lastLoginId as! String?
            }
    }
  

    func setPlaceHolerTextColor(_ fieldArray:Array<UITextField>!) {
            for textField in fieldArray {
                textField.tintColor = UIColor.white
                let attrituteString = NSMutableAttributedString(string : textField.placeholder!)
                attrituteString.setAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSMakeRange(0, attrituteString .string.characters.count))
                textField.attributedPlaceholder = attrituteString
        }
    }
    
    func resignAllTextField(sender:AnyObject){
        self.view.endEditing(true)
    }

    func dismissCurrentViewController(){
        isShowingLogin = false;
        if DWUserManager.shared.userInfo != nil {
            self.navigationController?.dismiss(animated: true, completion: {
                NotificationCenter.bk_postNotication(kNotificationRefreshMainData)
                if self.loginCompletions != nil{
                    self.loginCompletions!()
                }
            })
        }
    }
    
    class  func loginWithVC(vc:UIViewController,animated:Bool,completion:@escaping () -> Void) -> BaseNaviViewController {
            isShowingLogin = true
        let loginView = DWLoginViewController()
            loginView.loginCompletions = completion
        let naviVC = BaseNaviViewController(rootViewController:loginView)
            vc.present(naviVC, animated: animated, completion: completion)
        return naviVC
    }
    
    
    @IBAction func didClickLoginBtn(_ sender: UIButton) {

        self.accountView.alpha = 0.5
        self.passwordView.alpha = 0.5
        self.view.endEditing(true)

        let rt = DMRegularExpression.checkNewTelNumber(telNumber: self.accountField.text!)
        
        if !rt {
            HUD.textHUDInView(withText: "请输入正确的手机号码",inView:self.view)
            return
        }
        
        if (self.passwdField.text?.characters.count)! <= 0 {
            HUD.textHUDInView(withText: "请输入正确的手机号码",inView:self.view)
            return
        }
        
        let mailPattern = "^[A-Za-z0-9_]{6,16}"
        let matcher     = MyRegex(mailPattern)
        let passwordSet =  matcher.match(input:  self.passwdField.text!)
        if !passwordSet {
            HUD.textHUDInView(withText: "密码由6-16位数字和字母下划线组成",inView:self.view)
            return
        }
        
      //   HUD.normalHudInView(self.view)
      
        print("\(self.passwdField.text!)....\(self.accountField.text!)")
        
        let account     = Int64(self.accountField.text!)!*2
        let password    = "dwater\(account)diwinet"
        let passwordMD5 = password.md5
        let str2        = passwordMD5?.subString(to: 16)
        let str4        = str2?.lowercased()
        defaults.setValue(str4, forKey: "kmd516")
        print(self.passwdField.text!.md5.uppercased().md5)
        var paramDict : [String:Any] = ["yhzh": self.accountField.text!,
                                        "yhmm":self.passwdField.text!.md5.uppercased().md5.uppercased(),
                                        "sjxh":"iphone","dlfs":3]
        
        paramDict = DWBaseData.BaseDictionary(dics: paramDict)
        let temp  = DWBaseData.commonlyDictionary(dic: paramDict)
        
        NetworkRequest.sharedInstance.postAESRequest(urlString: "user/login.p", params: ["yhzh":self.accountField.text ?? "","infoMap":temp ?? ""], success: { (responseObject) in
            let data :[String : AnyObject] = responseObject["data"] as! [String : AnyObject]
            DWUserManager.shared.userInfo = DWUserInfo.parseFormDict(dict: data)
            defaults.set(self.accountField.text, forKey: "kSaveLastLoginUserID");
            DWUserInfo.saveToLocalFile(userInfo: DWUserManager.shared.userInfo)
            self.dismissCurrentViewController()
            
        }) { (error) in
            
            print("...\(error)")
            
        }
    }
    
}

extension DWLoginViewController:UITextFieldDelegate{
    
    func  textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let setRegex = "[A-Za-z0-9_]*"
        if textField == self.passwdField {
            let pred = NSPredicate(format:"SELF MATCHES \(setRegex)")
            let rt = pred.evaluate(with: string)
            if string.isEqual("\n") {
                return false
            }else if rt {
                if ((textField.text?.characters.count)! + string.characters.count) > 22{
                    return false
                }
                return true
            }else{
                return false
            }
        }else if textField == accountField && accountField.text?.characters.count == 1 && string.isEqual(""){
            self.passwdField.text = ""
        }
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField){
        if textField == self.accountField {
            self.accountView.alpha = 1
            self.accountView.alpha  = 0.5
            if textField.text?.characters.count == 0 {
                self.passwdField.text = ""
            }
        }else{
            self.accountView.alpha = 0.5
            self.accountView.alpha  = 1
        }
        
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }
    
    
    
}

